#include "server.h"

int tcpServerInit(char *ip, char *port, int *pSocketFd) {
    *pSocketFd = socket(AF_INET, SOCK_STREAM, 0);
    ERROR_CHECK(*pSocketFd, -1, "socket");
    struct sockaddr_in serverAddr;
    serverAddr.sin_family = AF_INET;
    int ret = inet_pton(AF_INET, ip, &serverAddr.sin_addr.s_addr);
    ERROR_CHECK(ret, -1, "inet_pton");
    serverAddr.sin_port = htons(atoi(port));
    int reuse = 1;
    ret = setsockopt(*pSocketFd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
    ERROR_CHECK(ret, -1, "setsockopt");
    ret = bind(*pSocketFd, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
    ERROR_CHECK(ret, -1, "bind");
    ret = listen(*pSocketFd, 10);
    ERROR_CHECK(ret, -1, "listen");
    return 0;
}

int acceptConnection(int socketFd, struct sockaddr_in *pClientAddr) {
    socklen_t len = sizeof(struct sockaddr_in);
    int netFd = accept(socketFd, (struct sockaddr *) pClientAddr, &len);
    ERROR_CHECK(netFd, -1, "accept");
    return netFd;
}

int epollAdd(int epollFd, int fd) {
    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = fd;
    int ret = epoll_ctl(epollFd, EPOLL_CTL_ADD, fd, &event);
    ERROR_CHECK(ret, -1, "EPOLL_CTL_ADD");
    return 0;
}

int epollDelete(int epollFd, int fd) {
    int ret = epoll_ctl(epollFd, EPOLL_CTL_DEL, fd, NULL);
    ERROR_CHECK(ret, -1, "EPOLL_CTL_DEL");
    return 0;
}
